# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2022/4/5 22:23 下午
# @Author : 曹庭
# @File : courseinfo.py
# @Software: PyCharm

from . import api
from course.utils.commons import login_required
from flask import g, current_app, jsonify, request
from course.utils.response_code import RET
from course.models import Course, Image
from course import db, constants
from course.utils.image_storage import storage
from sqlalchemy import or_, and_


@api.route("/upload_img", methods=["POST"])
@login_required
def upload_img():
    """
    上传图片并返回图片名称，不作数据存储
    参数：类目编号，标签编号，标题，正常价格，vip价格，课程介绍，课程目录，所有图片文件
    :return:
    """
    # 用户信息校验
    user_id = g.user_id
    if user_id != 1:
        return jsonify(code=RET.RIGHTSERR, msg="此账号无权限")

    # 获取前端参数
    image_file = request.files.get("file")
    print(image_file)

    image_data = image_file.read()

    # 调用七牛上传图片
    try:
        file_name = storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.THIRDERR, msg="上传图片失败")

    course_url = constants.QINIU_URL_DOMAIN + file_name
    course_url_dict = {'course_url': course_url, 'file_name': file_name}

    return jsonify(code=RET.OK, msg="请求成功", data=course_url_dict)


@api.route("/add_courses", methods=["POST"])
@login_required
def add_courses():
    """
    新增课程
    参数：类目编号，标签编号，标题，正常价格，vip价格，课程介绍，课程目录，所有图片文件
    :return:
    """
    # 用户信息校验
    user_id = g.user_id
    if user_id != 1:
        return jsonify(code=RET.RIGHTSERR, msg="此账号无权限")

    # 获取前端参数
    request_dict = request.get_json()
    image_files = request_dict.get("course_img")
    contents_id = request_dict.get("contents")
    label_id = request_dict.get("label")
    title = request_dict.get("course_title")
    normal_price = request_dict.get("normal_price")
    # vip_price = request_dict.get("vip_price")
    introduce = request_dict.get("courses_introduce")
    contents = request_dict.get("courses_contents")

    # 校验参数
    if not all([image_files, contents_id, label_id, title, normal_price, introduce, contents]):
        return jsonify(code=RET.PARAMERR, msg="参数不完整")

    # 将数据插入数据库
    course = Course(contents_id=contents_id, label_id=label_id, title=title, normal_price=normal_price,
                    introduce=introduce, contents=contents, index_image_url=image_files[0])

    try:
        db.session.add(course)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="数据库异常")

    # 查询数据库，获取生成的course_id
    try:
        course = Course.query.order_by(Course.create_time.desc()).first()
        course_id = course.id
        print(course_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="查询数据库异常")

    # 保存图片到数据中
    for image_file in image_files:
        if image_files.index(image_file) == 0:
            image = Image(course_id=course_id, screenshot_url=image_file, is_index_img=1)
        else:
            image = Image(course_id=course_id, screenshot_url=image_file, is_index_img=2)
        try:
            db.session.add(image)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(error=RET.DBERR, msg="保存图片信息失败")

    # 返回结果
    return jsonify(code=RET.OK, msg="新增课程成功")


@api.route("/edit_course", methods=["POST"])
@login_required
def edit_course():
    """
    修改课程
    参数：课程编号，类目编号，标签编号，标题，正常价格，vip价格，课程介绍，课程目录，课程主图片的路径
    :return:
    """
    # 用户信息校验
    user_id = g.user_id
    if user_id != 1:
        return jsonify(code=RET.RIGHTSERR, msg="此账号无权限")

    # 获取前端参数
    request_dict = request.get_json()
    course_id = request_dict.get("course_id")
    image_files = request_dict.get("course_img")
    contents_id = request_dict.get("contents")
    label_id = request_dict.get("label")
    title = request_dict.get("course_title")
    normal_price = request_dict.get("normal_price")
    vip_price = request_dict.get("vip_price")
    introduce = request_dict.get("courses_introduce")
    contents = request_dict.get("courses_contents")

    # 校验参数
    if not all([course_id, contents_id, image_files, label_id, title, normal_price, vip_price, introduce, contents]):
        return jsonify(code=RET.PARAMERR, msg="参数不完整")

    # 保存课程信息到数据库中
    try:
        Course.query.filter_by(id=course_id).update(
            {"contents_id": contents_id, "label_id": label_id, "title": title, "normal_price": normal_price,
             "vip_price": vip_price, "introduce": introduce, "contents": contents, "index_image_url": image_files[0]})
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="课程修改失败")

    # 删除image库中的图片数据
    try:
        images = Image.query.filter_by(course_id=course_id).all()
        for image in images:
            db.session.delete(image)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="数据库操作失败")

    # 保存图片到数据中
    for image_file in image_files:
        if image_files.index(image_file) == 0:
            image = Image(course_id=course_id, screenshot_url=image_file, is_index_img=1)
        else:
            image = Image(course_id=course_id, screenshot_url=image_file, is_index_img=2)
        try:
            db.session.add(image)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(error=RET.DBERR, msg="保存图片信息失败")

    # 返回结果
    return jsonify(code=RET.OK, msg="课程修改成功")


@api.route("/delete_course", methods=["POST"])
@login_required
def delete_course():
    """
    删除课程
    参数：课程编号
    :return:
    """

    # 用户信息校验
    user_id = g.user_id
    if user_id != 1:
        return jsonify(code=RET.RIGHTSERR, msg="此账号无权限")

    # 获取前端参数
    request_dict = request.get_json()
    course_id = request_dict.get("course_id")

    # 校验参数
    if not all([course_id]):
        return jsonify(code=RET.PARAMERR, msg="参数不完整")

    # 删除数据库课程表数据
    try:
        course = Course.query.filter_by(id=course_id).first()
        images = Image.query.filter_by(course_id=course_id).all()
        db.session.delete(course)
        for image in images:
            db.session.delete(image)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="数据库操作失败")

    # 返回结果
    return jsonify(code=RET.OK, msg="课程删除成功")


@api.route("/course_list", methods=["POST"])
# @login_required
def get_course_list():
    """
    查询条件查询
    :return:
    """
    # user_id = g.user_id

    # if user_id != 1:
    #     return jsonify(code=RET.RIGHTSERR, msg="此账号无权限")

    req_dict = request.get_json()
    curr = req_dict.get("curr")
    nums = req_dict.get("nums")
    searchParams = req_dict.get("searchParams")
    print(searchParams)

    course_id = searchParams["course_id"]
    course_title = searchParams["course_title"]
    label_id = searchParams["label_id"]
    contents_id = searchParams["contents_id"]

    filter_list = []

    if any([curr, nums, course_id, course_title, label_id, contents_id]):

        if course_id:
            print(course_id)
            filter_list.append(Course.id == course_id)
        if course_title:
            print(course_title)
            # filter_list.append(Course.title == course_title)
            filter_list.append(Course.title.like('%{}%'.format(course_title)))
        if label_id:
            print(label_id)
            filter_list.append(Course.label_id == label_id)
        if contents_id:
            print(contents_id)
            filter_list.append(Course.contents_id == contents_id)
        print(filter_list)
        try:
            paginate = Course.query.filter(*filter_list).paginate(page=curr, per_page=nums)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(code=RET.DBERR, msg="数据库查询失败")

        course_list = []

        courses = paginate.items
        print(courses)
        total = paginate.total
        for course in courses:
            course_dict = course.to_basic_dict()
            print(course_dict)
            course_list.append(course_dict)
        print(course_list)

        # 返回结果
        return jsonify(code=RET.OK, count=total, msg="所有课程信息获取成功", data=course_list)

    try:
        paginate = Course.query.paginate(page=curr, per_page=nums)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="数据库查询失败")

    course_list = []

    courses = paginate.items
    total = paginate.total
    for course in courses:
        course_dict = course.to_basic_dict()
        print(course_dict)
        course_list.append(course_dict)
    print(course_list)

    # 返回结果
    return jsonify(code=RET.OK, count=total, msg="所有课程信息获取成功", data=course_list)


@api.route("/get_course_detail", methods=["POST"])
# @login_required
def get_course_detail():
    """
    获取详情
    :return:
    """
    # course_id = request.form['course_id']
    req_dict = request.get_json()
    course_id = req_dict.get("course_id")
    print(course_id)

    # 校验参数
    if not course_id:
        return jsonify(code=RET.PARAMERR, msg="参数不完整")

    try:
        course = Course.query.filter_by(id=course_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="course数据库查询失败")

    courseinfo = course.to_basic_dict()

    try:
        images = Image.query.filter_by(course_id=course_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="image数据库查询失败")

    image_list = []
    for image in images:
        image_dict = image.to_dict()
        image_list.append(image_dict)

    # 返回结果
    return jsonify(code=RET.OK, msg="详情获取成功", data={"courseinfo": courseinfo, "imagelist": image_list})


@api.route("/get_course_all_list", methods=["POST"])
@login_required
def get_course_all_list():
    """
    获取所有课程列表
    :return:
    """
    try:
        courses = Course.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="数据库查询失败")

    course_list = []

    for course in courses:
        course_dict = course.to_basic_dict()
        course_list.append(course_dict)
        print(course_dict)
    print(course_list)

    # 返回结果
    return jsonify(code=RET.OK, msg="详情获取成功", data=course_list)


@api.route("/course/edit_image", methods=["POST"])
@login_required
def edit_image():
    """
    修改图片（暂不处理）
    :return:
    """
    image_file = request.files.get("course_img")
    course_id = request.form.get("course_id")
    image_id = request.form.get("image_id")
    is_index_img = request.form.get("is_index_img")

    # 校验参数
    if not all([image_file, course_id, image_id, is_index_img]):
        return jsonify(code=RET.PARAMERR, msg="参数不完整")

    image_data = image_file.read()

    # 调用七牛上传图片
    try:
        file_name = storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.THIRDERR, msg="上传图片失败")

    try:
        Image.query.filter_by(course_id=course_id, id=image_id, is_index_img=is_index_img).update(
            {"screenshot_url": file_name})
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR, msg="保存图片信息失败")

    try:
        image = Image.query.filter_by(course_id=course_id, id=image_id, is_index_img=is_index_img, ).first()
    except Exception as e:
        return jsonify(error=RET.DBERR, msg="查询数据库失败")

    image_dict = image.to_dict()

    # 返回结果
    return jsonify(code=RET.OK, msg="详情获取成功", data={"image_dict": image_dict})


@api.route("/course/delete_image", methods=["POST"])
@login_required
def delete_image():
    """
    删除图片（暂不处理）
    :return:
    """
    request_dict = request.get_json()
    course_id = request_dict.get("course_id")
    image_id = request_dict.get("image_id")
    image_id_update = request_dict.get("image_id_update")
    is_index_img = request_dict.get("is_index_img")

    # 校验参数
    if not all([course_id, image_id, image_id_update, is_index_img]):
        return jsonify(code=RET.PARAMERR, msg="参数不完整")

    try:
        image = Image.query.filter_by(course_id=course_id, id=image_id, is_index_img=is_index_img).first()
        if is_index_img == 1:
            Image.query.filter_by(course_id=course_id, id=image_id_update, is_index_img=2).update({"is_index_img": 1})
        db.session.delete(image)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(error=RET.DBERR, msg="删除图片信息失败")

    # 返回结果
    return jsonify(code=RET.OK, msg="图片删除成功")
